<template>
  <div class="employee-info">
    <el-card class="info-card">
      <template #header>
        <div class="card-header">
          <span>个人信息</span>
          <div class="button-group">
            <template v-if="!isEditing">
              <el-button type="primary" @click="handleEdit">
                <el-icon><EditPen /></el-icon>编辑
              </el-button>
              <el-button type="warning" @click="handleUpdateFace">
                <el-icon><Camera /></el-icon>更新人脸
              </el-button>
            </template>
            <template v-else>
              <el-button @click="cancelEdit">
                <el-icon><Close /></el-icon>取消
              </el-button>
              <el-button type="primary" @click="saveInfo">
                <el-icon><Check /></el-icon>保存
              </el-button>
            </template>
          </div>
        </div>
      </template>

      <div class="info-content">
        <div class="employee-avatar">
          <el-avatar :size="100" src="https://img.yzcdn.cn/vant/cat.jpeg" />
          <div class="employee-title">
            <h2>{{ form.name || '员工' }}</h2>
            <p>{{ form.position || '岗位信息' }} / {{ getDepartmentName(form.departmentId) }}</p>
          </div>
        </div>

        <el-divider content-position="center">基本信息</el-divider>

        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="120px"
          :disabled="!isEditing"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="员工编号">
                <el-input v-model="form.employeeNo" disabled>
                  <template #prefix>
                    <el-icon><Tickets /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="姓名" prop="name">
                <el-input v-model="form.name">
                  <template #prefix>
                    <el-icon><User /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="性别">
                <el-radio-group v-model="form.gender" disabled>
                  <el-radio :label="1">男</el-radio>
                  <el-radio :label="0">女</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="部门">
                <el-input :model-value="getDepartmentName(form.departmentId)" disabled>
                  <template #prefix>
                    <el-icon><OfficeBuilding /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="联系电话" prop="phoneNumber">
                <el-input v-model="form.phoneNumber">
                  <template #prefix>
                    <el-icon><Phone /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="form.email">
                  <template #prefix>
                    <el-icon><Message /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="职位" prop="position">
                <el-input v-model="form.position" disabled>
                  <template #prefix>
                    <el-icon><Pointer /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入职日期">
                <el-input v-model="form.hireDate" disabled>
                  <template #prefix>
                    <el-icon><Calendar /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-divider content-position="center">状态信息</el-divider>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="状态">
                <el-tag :type="form.status === 1 ? 'success' : 'info'">
                  {{ form.status === 1 ? '在职' : '离职' }}
                </el-tag>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否管理员">
                <el-tag :type="form.isAdmin ? 'warning' : 'info'">
                  {{ form.isAdmin ? '是' : '否' }}
                </el-tag>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-card>

    <!-- 修改密码对话框 -->
    <el-dialog v-model="passwordDialogVisible" title="修改密码" width="500px">
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
      >
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" show-password>
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" show-password>
            <template #prefix>
              <el-icon><Key /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" show-password>
            <template #prefix>
              <el-icon><Check /></el-icon>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="passwordDialogVisible = false">
            <el-icon><Close /></el-icon>取消
          </el-button>
          <el-button type="primary" @click="handleChangePassword">
            <el-icon><Check /></el-icon>确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 人脸录入对话框 -->
    <el-dialog v-model="faceDialogVisible" title="人脸录入" width="800px" :close-on-click-modal="false">
      <div class="face-register">
        <div class="camera-container">
          <video
            ref="videoRef"
            class="camera-preview"
            autoplay
            playsinline
            v-show="!capturedImage"
          ></video>
          <img v-if="capturedImage" :src="capturedImage" class="capture-preview" alt="captured" />
          <div class="face-mask" v-show="!capturedImage">
            <div class="face-frame"></div>
            <div class="tips">请将面部对准框内</div>
          </div>
        </div>
        <div class="camera-controls">
          <template v-if="!capturedImage">
            <el-button
              type="primary"
              @click="startCamera"
              v-if="!cameraStarted"
            >
              <el-icon><VideoCameraFilled /></el-icon> 开启摄像头
            </el-button>
            <el-button type="primary" @click="takePhoto" v-else>
              <el-icon><Camera /></el-icon> 拍照
            </el-button>
          </template>
          <template v-else>
            <el-button @click="retake">
              <el-icon><RefreshRight /></el-icon> 重新拍照
            </el-button>
            <el-button type="primary" @click="uploadFaceImage">
              <el-icon><Upload /></el-icon> 确认使用
            </el-button>
          </template>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Camera, 
  VideoCameraFilled, 
  User, 
  EditPen, 
  Close, 
  Check, 
  Phone, 
  Message, 
  Calendar, 
  Pointer, 
  OfficeBuilding, 
  Tickets, 
  RefreshRight, 
  Upload, 
  Lock, 
  Key,
  SwitchButton
} from '@element-plus/icons-vue'
import { getEmployeeInfo, updateEmployeeInfo, updateFace } from '@/api/employee/info'
import { useUserStore } from '@/store/user'

const userStore = useUserStore()
const isEditing = ref(false)
const formRef = ref(null)

// 个人信息表单
const form = ref({
  employeeNo: '',
  name: '',
  gender: 0,
  phoneNumber: '',
  email: '',
  departmentId: 0,
  position: '',
  status: 1,
  isAdmin: false,
})

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  phoneNumber: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' },
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' },
  ],
  position: [{ required: true, message: '请输入职位', trigger: 'blur' }],
}

// 密码修改相关
const passwordDialogVisible = ref(false)
const passwordFormRef = ref(null)
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
})

const passwordRules = {
  oldPassword: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' },
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
}

// 部门映射
const departmentMap = {
  0: '技术部',
  1: '人事部',
  2: '财务部',
}

// 获取部门名称
const getDepartmentName = (departmentId) => {
  return departmentMap[departmentId] || '未知部门'
}

// 获取员工信息
const fetchEmployeeInfo = async () => {
  try {
    const employeeNo = localStorage.getItem('employeeNo')
    if (!employeeNo) {
      ElMessage.error('获取员工编号失败')
      return
    }
    const res = await getEmployeeInfo(employeeNo)
    if (res) {
      Object.assign(form, res.data)
      form.value = res.data
    } else {
      ElMessage.error(res.data.message || '获取员工信息失败')
    }
  } catch (error) {}
}

// 编辑个人信息
const handleEdit = () => {
  isEditing.value = true
}

// 取消编辑
const cancelEdit = () => {
  isEditing.value = false
  // 重新获取数据
  fetchEmployeeInfo()
}

// 保存信息
const saveInfo = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate(async (valid) => {
      if (valid) {
        // 提交所需字段
        const updateData = {
          employeeNo: form.value.employeeNo,
          name: form.value.name,
          gender: form.value.gender,
          phoneNumber: form.value.phoneNumber,
          email: form.value.email,
          departmentId: form.value.departmentId,
          position: form.value.position,
        }
        const res = await updateEmployeeInfo(updateData)
        if (res.data) {
          ElMessage.success('提交成功，请等待管理员审核')
          isEditing.value = false
          fetchEmployeeInfo()
        } else {
          ElMessage.error(res.data?.message || '提交失败')
        }
      }
    })
  } catch (error) {
    console.error('保存员工信息出错：', error)
    ElMessage.error('保存失败')
  }
}

// 修改密码
const handleChangePassword = async () => {
  if (!passwordFormRef.value) return

  await passwordFormRef.value.validate((valid) => {
    if (valid) {
      ElMessage.success('密码修改成功')
      passwordDialogVisible.value = false
      // 重置密码表单
      passwordForm.oldPassword = ''
      passwordForm.newPassword = ''
      passwordForm.confirmPassword = ''
    }
  })
}

// 人脸录入相关
const faceDialogVisible = ref(false)
const videoRef = ref(null)
const cameraStarted = ref(false)
const capturedImage = ref(null)
const stream = ref(null)

// 开启摄像头
const startCamera = async () => {
  try {
    stream.value = await navigator.mediaDevices.getUserMedia({
      video: true,
      audio: false,
    })
    if (videoRef.value) {
      videoRef.value.srcObject = stream.value
      cameraStarted.value = true
    }
  } catch (error) {
    ElMessage.error('无法访问摄像头，请检查权限设置')
    console.error('摄像头访问错误：', error)
  }
}

// 拍照
const takePhoto = () => {
  const video = videoRef.value
  const canvas = document.createElement('canvas')
  canvas.width = video.videoWidth
  canvas.height = video.videoHeight
  const ctx = canvas.getContext('2d')
  ctx.drawImage(video, 0, 0, canvas.width, canvas.height)
  capturedImage.value = canvas.toDataURL('image/jpeg')
}

// 重新拍照
const retake = () => {
  capturedImage.value = null
}

// 关闭摄像头
const stopCamera = () => {
  if (stream.value) {
    stream.value.getTracks().forEach((track) => track.stop())
    stream.value = null
    cameraStarted.value = false
  }
}

// 将Base64图片转换为二进制Blob
const base64ToBlob = (base64Data) => {
  const base64WithoutPrefix = base64Data.substr(base64Data.indexOf(',') + 1)
  const byteString = atob(base64WithoutPrefix)
  const ab = new ArrayBuffer(byteString.length)
  const ia = new Uint8Array(ab)
  
  for (let i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i)
  }
  
  return new Blob([ab], { type: 'image/jpeg' })
}

// 打开人脸录入对话框
const handleUpdateFace = () => {
  faceDialogVisible.value = true
  startCamera()
}

// 上传人脸图片
const uploadFaceImage = async () => {
  if (!capturedImage.value) {
    ElMessage.warning('请先完成拍照')
    return
  }

  try {
    const employeeNo = localStorage.getItem('employeeNo')
    if (!employeeNo) {
      ElMessage.error('获取员工编号失败')
      return
    }

    // 将Base64格式的图片转换为二进制Blob
    const imageBlob = base64ToBlob(capturedImage.value)
    
    // 创建FormData对象并添加数据
    const formData = new FormData()
    formData.append('employeeNo', employeeNo)
    formData.append('faceImage', imageBlob, 'face.jpg')
    
    // 调用人脸更新API
    const res = await updateFace(formData)
    
    if (res.data.success) {
      ElMessage.success('人脸信息更新成功')
      faceDialogVisible.value = false
      stopCamera()
      capturedImage.value = null
    } else {
      ElMessage.error(res.data.message || '人脸更新失败，请重试')
    }
  } catch (error) {
    console.error('人脸更新错误:', error)
    ElMessage.error('人脸更新失败，请检查网络连接或稍后重试')
  }
}

// 监听对话框关闭
watch(faceDialogVisible, (newVal) => {
  if (!newVal) {
    stopCamera()
    capturedImage.value = null
  }
})

// 组件销毁时关闭摄像头
onBeforeUnmount(() => {
  stopCamera()
})

// 页面加载时获取员工信息
onMounted(() => {
  fetchEmployeeInfo()
})
</script>

<style scoped lang="scss">
.employee-info {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  
  .info-card {
    border-radius: 12px;
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.05);
    transition: all 0.3s ease;
    overflow: hidden;
    
    &:hover {
      box-shadow: 0 12px 32px rgba(24, 144, 255, 0.1);
      transform: translateY(-2px);
    }
  }
  
  .info-content {
    padding: 20px 10px;
  }
  
  .employee-avatar {
    display: flex;
    align-items: center;
    margin-bottom: 24px;
    padding: 16px;
    background: linear-gradient(to right, rgba(24, 144, 255, 0.05), rgba(24, 144, 255, 0.1));
    border-radius: 12px;
    
    .el-avatar {
      border: 3px solid #fff;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      transition: all 0.3s;
      
      &:hover {
        transform: scale(1.05);
        box-shadow: 0 6px 16px rgba(24, 144, 255, 0.2);
      }
    }
    
    .employee-title {
      margin-left: 24px;
      
      h2 {
        margin: 0 0 8px;
        font-size: 24px;
        color: #303133;
      }
      
      p {
        margin: 0;
        font-size: 15px;
        color: #606266;
      }
    }
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 0;
    
    span {
      font-size: 18px;
      font-weight: 600;
      color: #303133;
      position: relative;
      padding-left: 12px;
      
      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 4px;
        height: 18px;
        background: #1890ff;
        border-radius: 2px;
      }
    }

    .button-group {
      display: flex;
      gap: 12px;
    }
  }
  
  :deep(.el-divider) {
    margin: 24px 0;
    
    .el-divider__text {
      background: #f9f9f9;
      padding: 0 16px;
      font-size: 16px;
      font-weight: 600;
      color: #1890ff;
    }
  }

  :deep(.el-form) {
    padding: 24px 12px 8px;
  }

  :deep(.el-form-item__label) {
    font-weight: 600;
    color: #606266;
  }
  
  :deep(.el-input__wrapper) {
    border-radius: 8px;
    box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1) inset;
    transition: all 0.3s;
    
    &:hover, &.is-focus {
      box-shadow: 0 0 0 1px #1890ff inset;
    }
  }
  
  :deep(.el-input__prefix) {
    margin-right: 8px;
    
    .el-icon {
      color: #909399;
      font-size: 16px;
    }
  }
  
  :deep(.el-radio__label) {
    font-size: 14px;
    color: #606266;
  }
  
  :deep(.el-button) {
    border-radius: 8px;
    padding: 8px 20px;
    font-weight: 500;
    transition: all 0.3s;
    
    .el-icon {
      margin-right: 4px;
    }
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }
    
    &.el-button--primary {
      background: linear-gradient(135deg, #1890ff, #36a6ff);
      border-color: #1890ff;
      box-shadow: 0 4px 10px rgba(24, 144, 255, 0.2);
      
      &:hover {
        background: linear-gradient(135deg, #40a9ff, #5cbbff);
        border-color: #40a9ff;
        box-shadow: 0 6px 15px rgba(24, 144, 255, 0.3);
      }
      
      &:active {
        background: linear-gradient(135deg, #0e80ef, #1890ff);
      }
    }
    
    &.el-button--warning {
      background: linear-gradient(135deg, #ff9500, #ffa940);
      border-color: #ff9500;
      box-shadow: 0 4px 10px rgba(255, 149, 0, 0.2);
      
      &:hover {
        background: linear-gradient(135deg, #ffaa1f, #ffb957);
        border-color: #ffaa1f;
        box-shadow: 0 6px 15px rgba(255, 149, 0, 0.3);
      }
      
      &:active {
        background: linear-gradient(135deg, #e78a00, #ff9500);
      }
    }
  }
  
  :deep(.el-tag) {
    padding: 6px 12px;
    border-radius: 4px;
    font-weight: 500;
    
    &.el-tag--success {
      background-color: rgba(82, 196, 26, 0.1);
      border-color: rgba(82, 196, 26, 0.2);
      color: #52c41a;
    }
    
    &.el-tag--info {
      background-color: rgba(144, 147, 153, 0.1);
      border-color: rgba(144, 147, 153, 0.2);
      color: #909399;
    }
    
    &.el-tag--warning {
      background-color: rgba(250, 173, 20, 0.1);
      border-color: rgba(250, 173, 20, 0.2);
      color: #faad14;
    }
  }

  // 人脸注册部分
  .face-register {
    .camera-container {
      width: 100%;
      height: 400px;
      background: #000;
      position: relative;
      overflow: hidden;
      border-radius: 12px;
      box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);

      .camera-preview,
      .capture-preview {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      .face-mask {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.4);
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        backdrop-filter: blur(2px);

        .face-frame {
          width: 300px;
          height: 300px;
          border: 3px solid #1890ff;
          border-radius: 50%;
          margin-bottom: 20px;
          box-shadow: 0 0 0 5px rgba(24, 144, 255, 0.3),
                      0 0 20px rgba(24, 144, 255, 0.5);
          animation: pulse 2s infinite;
        }

        .tips {
          color: #fff;
          font-size: 16px;
          text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
          background: rgba(0, 0, 0, 0.4);
          padding: 8px 16px;
          border-radius: 20px;
          font-weight: 500;
        }
      }
    }

    .camera-controls {
      margin-top: 24px;
      display: flex;
      justify-content: center;
      gap: 20px;
    }
  }
  
  :deep(.el-dialog) {
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 12px 32px rgba(0, 0, 0, 0.1);
    
    .el-dialog__header {
      padding: 20px 24px;
      border-bottom: 1px solid #f0f0f0;
      margin: 0;
      
      .el-dialog__title {
        font-weight: 600;
      }
    }
    
    .el-dialog__body {
      padding: 24px;
    }
    
    .el-dialog__footer {
      padding: 16px 24px;
      border-top: 1px solid #f0f0f0;
    }
  }
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(24, 144, 255, 0.6);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(24, 144, 255, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(24, 144, 255, 0);
  }
}
</style>
